// 监听快捷键命令
chrome.commands.onCommand.addListener(async (command) => {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (!tab) return;

        await ensureContentScriptInjected(tab.id);

        if (command === 'capture-to-clipboard') {
            const response = await chrome.tabs.sendMessage(tab.id, { action: 'captureFrame' });
            if (response && response.success) {
                // 复制到剪贴板
                const clipboardResponse = await chrome.tabs.sendMessage(tab.id, {
                    action: 'copyToClipboard',
                    dataUrl: response.frameData.dataUrl
                });

                if (clipboardResponse && clipboardResponse.success) {
                    // 保存到历史记录
                    await addToHistory(response.frameData);
                    chrome.runtime.sendMessage({
                        type: 'capture-success',
                        action: 'clipboard',
                        dataUrl: response.frameData.dataUrl
                    });
                } else {
                    throw new Error('Failed to copy to clipboard');
                }
            } else {
                throw new Error(response?.error || 'Failed to capture frame');
            }
        } else if (command === 'capture-to-file') {
            const response = await chrome.tabs.sendMessage(tab.id, { action: 'captureFrame' });
            if (response && response.success) {
                await saveToFile(response.frameData);
                // 保存到历史记录
                await addToHistory(response.frameData);
                chrome.runtime.sendMessage({
                    type: 'capture-success',
                    action: 'file',
                    dataUrl: response.frameData.dataUrl
                });
            } else {
                throw new Error(response?.error || 'Failed to capture frame');
            }
        }
    } catch (error) {
        console.error('Error handling command:', error);
        chrome.runtime.sendMessage({
            type: 'capture-error',
            error: error.message
        });
    }
});

// 处理来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'addToHistory') {
        addToHistory(request.data)
            .then(() => sendResponse({ success: true }))
            .catch(error => sendResponse({ success: false, error: error.message }));
        return true; // 保持消息通道开放
    }
});

// 添加到历史记录
async function addToHistory(frameData) {
    const result = await chrome.storage.local.get('history');
    const history = result.history || [];
    
    const newEntry = {
        ...frameData,
        timestamp: new Date().toISOString()
    };
    
    history.unshift(newEntry);
    // 只保留最近20条记录
    if (history.length > 20) {
        history.pop();
    }
    
    await chrome.storage.local.set({ history });
}

// 保存文件
async function saveToFile(frameData) {
    // 获取当前设置
    const { settings = {} } = await chrome.storage.sync.get('settings');
    
    // 生成文件名
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const safeTitle = frameData.title.replace(/[\\/:*?"<>|]/g, '_').trim();
    
    let filename;
    if (settings.filenameFormat === 'custom' && settings.customFormat) {
        filename = settings.customFormat
            .replace('{title}', safeTitle)
            .replace('{time}', timestamp)
            .replace('{platform}', frameData.platform);
    } else {
        switch (settings.filenameFormat) {
            case 'time_title':
                filename = `${timestamp}_${safeTitle}`;
                break;
            case 'title':
                filename = safeTitle;
                break;
            case 'title_time':
            default:
                filename = `${safeTitle}_${timestamp}`;
        }
    }
    
    filename += `.${settings.imageFormat || 'png'}`;
    
    // 下载文件
    await chrome.downloads.download({
        url: frameData.dataUrl,
        filename: filename
    });
}

// 检查并注入内容脚本
async function ensureContentScriptInjected(tabId) {
    try {
        // 尝试发送消息来检查内容脚本是否已加载
        await chrome.tabs.sendMessage(tabId, { action: 'ping' });
    } catch (error) {
        // 如果消息发送失败，注入内容脚本
        await chrome.scripting.executeScript({
            target: { tabId: tabId },
            files: ['content.js']
        });
        
        // 等待脚本初始化
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}
